#ifndef SERSOCKET_H
#define SERSOCKET_H
#include <QHostInfo>
#include <QTcpServer>
#include <QTcpSocket>
#include <QFile>
#include <QFileInfo>
#include <QTimer>
#include <QTime>
#include <QElapsedTimer>
#include <QVector>
#include <QJsonDocument>
#include <QJsonParseError>
#include <QJsonObject>
#include <QJsonArray>
#include <QThread>
#include <QQueue>

typedef struct{
    QByteArray info;
    QString fpath;
    QString fname;
    QByteArray uid;
    int sz;
} file_box;

class QSoundEffect;

class SerSocket : public QTcpSocket
{
    Q_OBJECT
public:
    SerSocket(QObject *parent = NULL);
    ~SerSocket();

    void ClientConnectToHost(const QString &address, quint16 port);

    void ClientGetUnreadMsg();
    void ClientGetUnreadFile();

    void ClientSendingFRequese(const QString &address,const QString& fname,const QByteArray& info,const int& sz,const QString& type);

    void ClientSendingText(const QByteArray &data,const uint16_t& cmd);
    void ClientSendingFile(const file_box& fbox);
    void ClientSendingIcon(const file_box& fbox);

//    void ClientSendingRPath(const QString &data);

    bool IsOnline();
    void Jump(const QByteArray& bag);

signals:
    void SignalSign();
    void Updatefinish();
    void FileSucccess();

    void GetMsgId(const int& id);

    void ServerSendList(const QJsonArray& list_bag,const QJsonArray& group_bag,const int edition);

    void ServerSendUnreadMsg(const QJsonArray& msg_bag);
    void ServerSendUnreadFile(const QJsonArray& msg_bag);
    void ServerSendUpdateList(const QJsonArray& list_bag,const QJsonArray& group_bag);

//    void ServerFileinfo(const QString data,const QString& fid);
    void SignalRcvPrepare();

    void Signal(const QString data);
    void SignalUID(const QString data);

    void showPicture(const QString& path);

    void sentfile();
    void jindu(int val ,QString fileName);
    void r_jindu(int val ,QString fileName);
    void sentfiler();

    void SignalSignError(const QString& error);

    void sentRcvRequese(const QByteArray &data,const uint16_t& cmd);

private slots:
    void on_readyread();
    void on_sentfile();
    void on_sentfilebag();
    quint64 on_send(const QByteArray& msg);
private:
    //标记连接情况
    bool m_bOnLine = false;
    bool used = false;
    void releaselock(){
        //QThread::msleep(1);
        this->disconnectFromHost();
        used = false;}

    //发送文件与接收文件相关参数
    QString fileName;
    QQueue<file_box> file_que;

    QFile* file;
    qint64 fileSize;
    qint64 sendSize;
    QByteArray f_uid;
    QString f_name;

    QString rfileName;
    QFile* rfile;
    qint64 rfileSize;
    QString r_type;
    QString rfilePath;
    qint64 rcvSize;
    QByteArray r_info;

    QElapsedTimer mTime;
    int last_time = 0;
    uint16_t rbag = 0x0800;
    uint16_t fbag = 0x00FF;


    QByteArray fram;

    QByteArray lastbuffer;
    bool has_last = false;

    QSoundEffect* effect;
};

#endif // SERSOCKET_H
